const router = require('express').Router()
const tokenUtils = require('../utils/token_utils')
const RandomAPI = require('../utils/random_utils')
const { Account, UserInfo } = require('../database/utils')
const { ApiResponse, tokenMiddleware } = require('./api_response')
const md5 = require('md5')

const random = new RandomAPI()

// 注册
router.post('/register', async (req, res) => {
    let apiRes = new ApiResponse(res);
    let findUser = await Account.findOne({
        where: { username: req.body.username }
    })
    if (findUser) {
        apiRes.fail('账号已存在');
        return
    }
    let tempAccount = random.uniqueId()
    let createUser = await Account.create({
        account: tempAccount,
        username: req.body.username,
        password: md5(req.body.password)
    })
    await UserInfo.create({
        account: tempAccount,
        nickname: random.randomName('user'),
        avatar: '',
        mobile: '',
        email: '',
        userType: 0
    })

    if (createUser) {
        apiRes.success("注册成功");
    } else {
        apiRes.error("注册失败");
    }
})

// 登录
router.post('/login', async (req, res) => {
    let apiRes = new ApiResponse(res);
    let findUser = await Account.findOne({ username: req.body.username })
    if (findUser) {
        if (findUser.password == md5(req.body.password)) {
            let token = tokenUtils.createToken({
                id: findUser.id,
                account: findUser.account
            }, '15day');
            apiRes.success({ 'token': token }, '登录成功')
        } else {
            apiRes.error('账号密码错误')
        }
    } else {
        apiRes.fail('用户名不存在，请先注册')
    }
})

// 获取用户信息
router.get('/getUserInfo', tokenMiddleware, async (req, res) => {
    let apiRes = new ApiResponse(res);
    let token = req.get('Authorization').split(' ')[1]
    //console.log(' 获取用户信息 获取到的 token ' + token)
    let userData = tokenUtils.decodeData(token)
    if (userData.success) {
        let user_account = userData.data.account
        let userInfo = await UserInfo.findOne({ account: user_account })
        if (userInfo) {
            apiRes.success(userInfo.dataValues, '登录成功')

        } else {
            apiRes.fail('用户名不存在，请先注册')
        }

    }
    else {
        apiRes.validateFailed('登录信息已失效，请重新登录', 400)
    }
})

module.exports = router